<?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    /**
     * @property  Goods_model   goods_model
     * @property  Eccang        eccang
     * @property  good          good
     * @property  siteweb_model siteweb_model
     */
    class Product extends Admin_Controller
    {
        /**
         * 产品列表页
         * author: walker
         * Date: 2019/11/6
         * Time: 15:33
         * Note:
         */
        public function index()
        {

            $this->load->model('goods_model');
            $this->load->model('order_model');
            $this->load->model('category_model');
            $this->load->model('siteweb_model');
            $this->load->model('admin_model');

            $this->load->library('pagination');

            $assoc = $this->uri->uri_to_assoc();

            $is_clear = intval($this->input->get('clear'));
            if ($is_clear){
                $_COOKIE['export_goods'] = array();
                setcookie("export_goods", '', time() - 1);
                setcookie("export_goods", '', time() - 86400, '/');
            }

            unset($_GET['clear']);

            $siteweb = $this->siteweb_model->siteweb_option();
            //$cate_option = $this->category_model->cate_option();
            $cat_one = $this->category_model->cat_one();

            $this->load->library('good');
            $cat_one = $this->good->get_cat_cache_count($cat_one);

            $admin_name = $this->admin_model->admin_option(['group' => 1,'is_del'=>0]);
            $goods_typestyle = $this->db->from('goods_typestyle')->where(['pid'=>0,'is_del'=>0])->get()->result_array();
            foreach ($goods_typestyle as $key => $value) {
                $goods_type = $this->db->from('goods_typestyle')->where(['pid'=>$value['id'],'is_del'=>0])->get()->result_array();
                $goods_typestyle[$key]['val'] = $goods_type;
            }
            $_param_option = array(
                'goods_name'  => array(
                    'col'         => 'col-lg-3',
                    'type'        => 'text',
                    'placeholder' => '输入产品名称、货号',
                ),
                // 'cate_cat' => array(
                //     'col' => 'col-lg-2',
                //     'type' => 'option',
                //     'placeholder' => '顶级分类',
                //     'option' => $cat_one['arr']
                // ),
                'cate_name'   => array(
                    'col'         => 'col-lg-2',
                    'type'        => 'option_cat',
                    'placeholder' => '选择分类',
                    'option'      => $cat_one,
                ),
                'is_on_sales' => array(
                    'col'         => 'col-lg-1',
                    'type'        => 'option',
                    'placeholder' => '商品上下架',
                    'option'      => array(
                        1 => '上架',
                        2 => '下架',
                    ),
                ),
                'channel_id'  => array(
                    'col'         => 'col-lg-1',
                    'type'        => 'option',
                    'placeholder' => '渠道',
                    'option'      => array(
                        1 => '外网',
                        2 => '竞争对手',
                        3 => '供应商1688',
                    ),
                ),
                'admin_id'    => array(
                    'col'         => 'col-lg-2',
                    'type'        => 'option',
                    'placeholder' => '请选择开发员',
                    'option'      => $admin_name,
                ),
                'is_tort'     => array(
                    'col'         => 'col-lg-1',
                    'type'        => 'option',
                    'placeholder' => '选择侵权',
                    'option'      => array(
                        1 => '侵权',
                        2 => '不侵权',
                    ),
                ),
                'is_on_sale'  => array(
                    'col'         => 'col-lg-1',
                    'type'        => 'option',
                    'placeholder' => '站点上下架',
                    'option'      => array(
                        1 => '是',
                        2 => '否',
                    ),
                ),
                'siteweb'     => array(
                    'col'         => 'col-lg-2',
                    'type'        => 'option',
                    'placeholder' => '请选择网站',
                    'option'      => $siteweb,
                ),
                'add_time'    => array(
                    'col'         => 'col-lg-4',
                    'type'        => 'dpd_time',
                    'placeholder' => '上传时间',
                ),
                'type_style'    => array(
                    'col'         => 'col-lg-12',
                    'type'        => 'checkbox',
                    'placeholder' => '风格',
                    'option'      => $goods_typestyle,
                ),
            );
            $type_style = $this->input->get('type_style');
            if($type_style){
                $type_style = implode(',',$type_style);
            }
            $_param = array(
                'goods_name'     => trim($this->input->get('goods_name')),
                'cate_name'      => intval($this->input->get('cate_name')),
                'admin_id'       => intval($this->input->get('admin_id')),
                'is_on_sale'     => intval($this->input->get('is_on_sale')),
                'is_on_sales'    => intval($this->input->get('is_on_sales')),
                'siteweb'        => intval($this->input->get('siteweb')),
                'add_time_start' => trim($this->input->get('add_time_start')),
                'add_time_end'   => trim($this->input->get('add_time_end')),
                'is_tort'        => trim($this->input->get('is_tort')),
                'page'           => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0,
                'channel_id'     => trim($this->input->get('channel_id')),
                'type_style'     => $type_style,
            );

            $config['base_url']         = base_url('Product/') . 'index/page/';
            $config['total_rows']       = $this->goods_model->goods_num($_param);
            $config['num_links']        = 6;
            $config['per_page']         = $this->goods_model->limit_rows;
            $config['use_page_numbers'] = true;
            $this->pagination->initialize($config);

            $_goods_list = $this->goods_model->goods_list($_param);

            foreach ($_goods_list as $key => $row) {
                $_goods_list[$key]['goods_num'] = $this->order_model->order_goods_num($row['shopify_id']);
                $this->load->model('tagslist_model');
                // $tagslist                    = $this->tagslist_model->tags_in($row['tags']);
                // $_goods_list[$key]['tags']   = $tagslist;
                $fabric                      = $this->db->from('fabric')->select('fabric_name')->where(['id' => $row['fabric_id']])->get()->row_array();
                $_goods_list[$key]['fabric'] = $fabric['fabric_name'];
                $color_size                  = $this->db->from('goods_sku')->where(['goods_id' => $row['goods_id'], 'is_delete' => 0])->select('color,size')->get()->result_array();
                foreach ($color_size as $k => $v) {
                    $color[] = $v['color'];
                    $size[]  = $v['size'];
                }

                if ($color){
                    $color = array_unique($color);
                }

                if ($size){
                    $size = array_unique($size);
                }

                $_goods_list[$key]['color']         = $color;
                $_goods_list[$key]['size']          = $size;
                $purchase_name                      = $this->db->from('purchase')->where(['e_id' => $row['purchase_id']])->select('purchase_name')->get()->row_array();
                $_goods_list[$key]['purchase_name'] = $purchase_name['purchase_name'];
            }


            $_action_link = array(
                array('href' => base_url('Product/off_shelve_list/'), 'name' => '产品下架'),
                array('href' => base_url('Product/set'), 'name' => '添加产品'),
            );


            $bigcom_siteweb = $this->siteweb_model->siteweb_option(0, array('type' => 2));
            $siteweb        = $this->siteweb_model->siteweb_option(1, array('type' => 1));
            $uee_site       = $this->siteweb_model->siteweb_option(0, array('type' => 3));

            $_param['is_on_sales'] = $_param['is_on_sales'] ?: 1;

            $data = array(
                'goods_list'     => $_goods_list,
                'action_link'    => $_action_link,
                'pages'          => $this->pagination->create_links(),
                'site_option'    => $this->siteweb_model->siteweb_option(),
                'param_option'   => $_param_option,
                'siteweb'        => $siteweb,
                'siteweb_json'   => json_encode($siteweb),
                'uee_sitejson'   => json_encode($uee_site),
                'bigcom_siteweb' => json_encode($bigcom_siteweb),
                'param'          => $_param,
                //'cat_res' => $cat_one['res']

            );
            //        echo "<pre>";
            //        print_r($_param_option);
            //        die();
            $this->load->view('product_list', $data);
        }

        //修改侵权
        public function tort()
        {
            $goods_id = $this->input->post('goods_id');
            $this->load->model('goods_model');
            $res = $this->goods_model->goodds_tort($goods_id);
            echo $res;
        }

        public function salegoods()
        {
            $this->load->model('goods_model');
            $this->load->model('goods_sku_model');
            $this->load->model('order_model');
            $this->load->model('category_model');
            $this->load->model('siteweb_model');

            $this->load->library('pagination');

            $assoc = $this->uri->uri_to_assoc();

            $siteweb = $this->siteweb_model->siteweb_option(1);

            $cate_option = $this->category_model->cate_option();

            $_param_option = array(
                'goods_name' => array(
                    'col'         => 'col-lg-4',
                    'type'        => 'text',
                    'placeholder' => '输入产品名称、货号',
                ),
                'cate_name'  => array(
                    'col'         => 'col-lg-2',
                    'type'        => 'option',
                    'placeholder' => '选择分类',
                    'option'      => $cate_option,
                ),
                'order_time' => array(
                    'col'         => 'col-lg-4',
                    'type'        => 'dpd_time',
                    'placeholder' => '销量时间',
                ),
                'goods_time' => array(
                    'col'         => 'col-lg-4',
                    'type'        => 'dpd_time',
                    'placeholder' => '上传时间',
                ),
                'in_time'    => array(
                    'col'         => 'col-lg-4',
                    'type'        => 'dpd_time',
                    'placeholder' => '上架时间',
                ),
                'siteweb'    => array(
                    'col'         => 'col-lg-2',
                    'type'        => 'option',
                    'placeholder' => '选择网站',
                    'option'      => $siteweb,
                ),
            );

            $_param = array(
                'goods_name'       => trim($this->input->get('goods_name')),
                'web_order_by'     => intval($_COOKIE['order_sort']),
                'cate_name'        => $this->input->get('cate_name'),
                'order_time_start' => trim($this->input->get('order_time_start')),
                'order_time_end'   => trim($this->input->get('order_time_end')),
                'goods_time_start' => trim($this->input->get('goods_time_start')),
                'goods_time_end'   => trim($this->input->get('goods_time_end')),
                'in_time_start'    => trim($this->input->get('in_time_start')),
                'in_time_end'      => trim($this->input->get('in_time_end')),
                'page'             => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0,
                'siteweb'          => intval($this->input->get('siteweb')),
            );


            $config['base_url']         = base_url('Product/') . 'salegoods/' . ($_param['order_sorting'] ? "order_sorting/{$_param['order_sorting']}/" : '') . 'page/';
            $config['total_rows']       = $this->goods_model->goods_num($_param);
            $config['num_links']        = 6;
            $config['per_page']         = $this->goods_model->limit_rows;
            $config['use_page_numbers'] = true;
            $this->pagination->initialize($config);

            $_goods_list = $this->goods_sku_model->goods_sku_color_sale($_param);

            $_action_link = array(
                array('href' => base_url('Order/order_five_sum'), 'name' => '新销售数据'),
                array('href' => base_url('SalesCount/total_sales'), 'name' => '总销量'),
                array('href' => base_url('SalesCount/index'), 'name' => '新版销量图'),
            );

            $_siteweb = $this->siteweb_model->siteweb_option(1);

            $siteweb      = array();
            $siteweb_is_a = 0;
            foreach ($_siteweb as $k => $val) {

                $siteweb[$k] = array(
                    'val'    => $val,
                    'is_acc' => intval($_COOKIE[$val]),
                );

                $siteweb_is_a += $_COOKIE[$val] == 1 ? 0 : 1;
            }

            $data = array(
                'goods_list'   => $_goods_list,
                'action_link'  => $_action_link,
                'pages'        => $this->pagination->create_links(),
                'site_option'  => $this->siteweb_model->siteweb_option(),
                'param_option' => $_param_option,
                'siteweb'      => $siteweb,
                'siteweb_json' => json_encode($_siteweb),
                'siteweb_is_a' => $siteweb_is_a,
                'param'        => $_param,
            );


            $this->load->view('product_salegoods', $data);
        }

        public function ajax_sales()
        {
            $this->load->model('goods_model');
            $this->load->model('order_model');
            $this->load->model('category_model');
            $this->load->model('siteweb_model');

            $pg_id           = $this->input->get('pg_id');
            $sale_time_start = $this->input->get('sale_time_start');
            $sale_time_end   = $this->input->get('sale_time_end');

            $goods = $this->goods_model->goods_sale_info($pg_id, $sale_time_end, $sale_time_start);

            $this->load->view('library/a', $goods);

        }

        public function salegoods_excel()
        {
            $assoc = $this->uri->uri_to_assoc();
            $this->load->model('goods_sku_model');
            $_param      = array(
                'goods_name'       => trim($this->input->get('goods_name')),
                'web_order_by'     => intval($_COOKIE['order_sort']),
                'cate_name'        => $this->input->get('cate_name'),
                'order_time_start' => trim($this->input->get('order_time_start')),
                'order_time_end'   => trim($this->input->get('order_time_end')),
                'goods_time_start' => trim($this->input->get('goods_time_start')),
                'goods_time_end'   => trim($this->input->get('goods_time_end')),
                'in_time_start'    => trim($this->input->get('in_time_start')),
                'in_time_end'      => trim($this->input->get('in_time_end')),
                'siteweb'          => intval($this->input->get('siteweb')),
                'page'             => $this->input->get('page') > 0 ? $this->input->get('page') - 1 : 0,
            );
            $excel_psge  = !$this->input->get('excel_psge') ? $excel_psge = 1 : $this->input->get('excel_psge');
            $_goods_list = $this->goods_sku_model->goods_sku_color_sale($_param, 99, $excel_psge);
            // print_r($_goods_list);die;

            $this->load->model('siteweb_model');
            $_siteweb = $this->siteweb_model->siteweb_option(1);
            $letter   = ['D1', 'E1', 'F1', 'G1', 'H1', 'I1', 'J1', 'K1', 'L1', 'M1', 'N1', 'O1', 'P1', 'Q1', 'R1', 'S1', 'T1', 'U1', 'V1', 'W1', 'X1', 'Y1', 'Z1'];
            foreach ($_siteweb as $key => $val) {
                $arr['zhan']    = $val;
                $arr['zhan_id'] = $key;
                $res[]          = $arr;

            }
            foreach ($res as $key => $val) {
                foreach ($letter as $k => $v) {
                    if ($key == $k){
                        $res[$key]['zimu'] = $v;
                    }
                }
            }

            $xia = ['D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

            foreach ($res as $key => $val) {
                foreach ($xia as $k => $v) {
                    if ($key == $k){
                        $res[$key]['zimus'] = $v;
                    }
                }
            }
            $this->load->library('PHPExcel');
            $objPHPExcel = new \PHPExcel ();
            // Set document properties
            $objPHPExcel->getProperties()->setCreator("zend")-> // 作者
            setLastModifiedBy("zend")-> // 最后一次保存者
            setTitle("Office 2007 XLSX Document")-> // 标题
            setSubject("Office 2007 XLSX Document")-> // 主题
            setDescription("document for Office 2007 XLSX, generated using PHP classes.")-> // 备注
            setKeywords("office 2007 openxml php")-> // 标记
            setCategory("result file"); // 类别
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth('13');// 设置列宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth('30');
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth('13');
            foreach ($xia as $key => $val) {
                $objPHPExcel->getActiveSheet()->getColumnDimension($val)->setWidth('13');
            }

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '总销量'); // 第一行A列值
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1', '图片'); // 第一行A列值
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C1', '货号'); // 第一行B列值
            foreach ($res as $k => $v) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($v['zimu'], $v['zhan']);
            }
            $i = 1;
            foreach ($_goods_list as $key => $val) {
                $i = $i + 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . ($i), ' ' . $val['or_goods_number']);
                /* 实例化插入图片类 */
                $objDrawing = new \PHPExcel_Worksheet_Drawing ();
                /* 设置图片路径 切记：只能是本地图片 D:\phpstudy\PHPTutorial\WWW\application\controllers\1.jpgalbum/2018/04/17/86f185ceb49ba618fc096309dc568925.jpg*/
                //echo substr($v['original_img'],1);die;
                $img = substr($val['original_img'], 1);

                if (is_file($img)){
                    $objDrawing->setPath($img);
                } else {
                    $objDrawing->setPath('album/2019/05/shopify/bucunzai.jpg');
                }
                //$objDrawing->setPath ( 'D:\phpstudy\PHPTutorial\WWW\application\controllers\1.jpg' );
                /* 设置图片高度 */
                $objDrawing->setHeight(100);
                /* 设置图片要插入的单元格位置 */
                $objDrawing->setCoordinates('B' . ($i)); // 这里第二行C列
                // 写入图片在指定格中的X坐标值
                $objDrawing->setOffsetX(20);
                // 写入图片在指定格中的Y坐标值
                $objDrawing->setOffsetY(20);
                // 设置旋转角度
                // $objDrawing->setRotation(20);
                $objDrawing->getShadow()->setVisible(true);
                $objDrawing->getShadow()->setDirection(50);
                $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());

                // 设置单元格高度
                $objPHPExcel->getActiveSheet()->getRowDimension($i)->setRowHeight(100);

                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . ($i), ' ' . $val['goods_sn']);

                foreach ($res as $k => $v) {
                    if ($val['web_g_number'][$v['zhan_id']]){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($v['zimus'] . ($i), ' ' . $val['web_g_number'][$v['zhan_id']]['web_goods_number']);
                    } else {
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($v['zimus'] . ($i), ' ' . ' ');
                    }
                }
            }

            $objPHPExcel->getActiveSheet()->setTitle('Simple');

            // Set active sheet index to the first sheet, so Excel opens this as the first sheet
            $objPHPExcel->setActiveSheetIndex(0);

            // 重定向输出到客户端的Web浏览器 (Excel2007)
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="导出商品.xlsx"');
            header('Cache-Control: max-age=0');

            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');

        }


        public function set()
        {

            $this->load->library('session');

            $this->load->model('goods_model');
            $this->load->model('admin_model');
            $this->load->model('goods_type_model');
            $this->load->model('suppliers_model');
            $this->load->model('category_model');
            $this->load->model('size_model');
            $this->load->model('color_model');
            $this->config->load('website_common');

            $assoc = $this->uri->uri_to_assoc();

            $this->load->library('sys_message');
            $this->load->library('ali');

            $goods_id = intval($assoc['goods_id']);

            $size   = $this->size_model->size_option();
            $colors = $this->color_model->color_option();

            $goods = array();
            if ($goods_id){
                $goods = $this->goods_model->goods_info($assoc['goods_id'], 1);
                !$goods && $this->sys_message->wrong('产品不存在!');

                $goods['goods_attr'] = json_decode($goods['goods_attr'], true);
            }

            $type_option      = $this->goods_type_model->type_option();
            $suppliers_option = $this->suppliers_model->suppliers_option();
            $cate_option      = $this->category_model->cate_option();
            $size_option      = $size['option'];
            $color_option     = $colors['option'];
            $admin_id         = $this->session->userdata('admin_id');
            $goods_sn         = $this->goods_model->goods_sn_max($admin_id);
            $admin_name       = $this->admin_model->admin_option();
            $this->config->load('data_field');
            $sale_status = $this->config->item('sale_status');//销售状态

            if ($_POST){

                $sku_pro_data = array();
                foreach ($_POST['sku']['size'] as $key => $value) {

                    $sku_key_str = $value . $_POST['sku']['color'][$key];
                    if ($sku_pro_data[$sku_key_str]){
                        $this->sys_message->wrong('颜色(' . $_POST['sku']['color'][$key] . ')尺码(' . $value . ')重复!');
                    }

                    if (empty($_POST['sku']['color'][$key])){
                        $this->sys_message->wrong('颜色未选择!');
                    }
                    if (empty($value)){
                        $this->sys_message->wrong('尺码未选择!');
                    }

                    $sku_pro_data[$sku_key_str] = true;
                }

                $config = $this->config->item('upload');
                $this->load->library('upload', $config);
                $this->load->library('image_lib');

                //480*640图片
                $configLarge = $this->config->item('configLarge');
                //260*350图片
                $configThumb = $this->config->item('configThumb');

                $attr = array(
                    'attr_title' => $this->input->post('attr_title'),
                    'attr_val'   => $this->input->post('attr_val'),
                );
                $tags = $this->input->post('tags');
                $tags = !empty($tags) ? implode(',', $tags) : '';

                $data = array(
                    'goods_name'       => trim($this->input->post('goods_name')),
                    'cn_name'          => trim($this->input->post('cn_name')),
                    'cat_id'           => intval($this->input->post('cat_id')),
                    'type_id'          => intval($this->input->post('type_id')),
                    'sale_status'      => intval($this->input->post('sale_status')),//销售状态
                    'suppliers_id'     => intval($this->input->post('suppliers_id')),
                    'style_type'       => intval($this->input->post('style_type')),
                    'goods_sn'         => $this->goods_model->goods_sn_max($admin_id),
                    'goods_weight'     => trim($this->input->post('goods_weight')),
                    'market_price'     => trim($this->input->post('market_price')),
                    'supp_url'         => trim($this->input->post('supp_url')),
                    'supp_sn'          => trim($this->input->post('supp_sn')),
                    'shop_price'       => trim($this->input->post('shop_price')),
                    'in_price'         => trim($this->input->post('in_price')),
                    'body_html'        => trim($this->input->post('summernote')),
                    'compare_at_price' => trim($this->input->post('compare_at_price')),
                    'goods_attr'       => json_encode($attr),
                    'is_testing'       => $this->input->post('is_testing'),
                    'tags'             => $tags,
                    'channel_id'       => $this->input->post('channel_id'),
                );

                if ($goods){
                    $data['goods_sn'] = $goods['goods_sn'];
                }

                !$admin_id && $this->sys_message->wrong('请选择开发员!');
                !$data['goods_name'] && $this->sys_message->wrong('请填写英文名称!');
                !$data['type_id'] && $this->sys_message->wrong('请选择产品类型!');
                !$data['suppliers_id'] && $this->sys_message->wrong('请选择供应商!');
                !$data['supp_url'] && $this->sys_message->wrong('请填写产品链接!');
                !$data['in_price'] && $this->sys_message->wrong('请填写进货价!');
                !$data['shop_price'] && $this->sys_message->wrong('请填写售价!');


                $post_sku = $this->input->post('sku');

                !$post_sku && $this->sys_message->wrong('请选择sku信息!');

                $sku = array();
                foreach ($post_sku as $key => $item) {
                    foreach ($item as $k => $val) {
                        $sku[$k][$key] = $val;
                    }
                }
                if ($goods['shopify_id'] > 0){
                    $_goods_sku   = $goods['sku'];
                    $goods['sku'] = array();
                    foreach ($_goods_sku as $sku_row) {
                        $_sku_sn                = strtolower(str_replace(' ', '', $sku_row['sku_sn']));
                        $goods['sku'][$_sku_sn] = $sku_row;
                    }

                    foreach ($sku as $k => $item) {
                        $sku_num_sn = preg_replace("/[a-zA-Z]+/", "", $data['goods_sn']) . $colors['color'][$item['color']]['color_num'] . $size['size'][$item['size']]['size_num'];

                        $sku_sn = strtolower(str_replace(' ', '', "{$goods['goods_id']}-{$item['color']}-{$item['size']}"));

                        $r = array_filter($sku, function($t) use ($sku_num_sn) {
                            return $t['sku_num_sn'] == $sku_num_sn;
                        });
                        if ($r || !$item['color'] || !$item['size']){
                            unset($sku[$k]);
                            continue;
                        }

                        $sku[$k]['sku_num_sn'] = $goods['sku'][$sku_sn] ? $goods['sku'][$sku_sn]['sku_num_sn'] : $sku_num_sn;
                        $sku[$k]['handle']     = $goods['sku'][$sku_sn] ? 'update' : 'insert';
                        $sku[$k]['sku_sn']     = str_replace(' ', '', $item['color']) . '-' . $item['size'];
                        $sku[$k]['sku_id']     = intval($goods['sku']['sku_id']);
                    }
                } else {

                    $ml = preg_replace("/[0-9]/", "", $data['goods_sn']);

                    $goods_sku_model = get_model('goods_sku_model');
                    if ($ml == 'ML'){
                        $sku_filter = ['goods_id' => $goods_id];
                        foreach ($sku as $k => $item) {
                            $sku_num_sn = preg_replace("/[a-zA-Z]/", "", $data['goods_sn']) . $colors['color'][$item['color']]['color_num'] . $size['size'][$item['size']]['size_num'];

                            $sku_filter['color'] = $item['color'];
                            $sku_filter['size']  = $item['size'];

                            $sku_row = $goods_sku_model->j_row($sku_filter);

                            if (empty($sku_row)){
                                if ($item['sku_id']){
                                    $old_sku_row          = $goods_sku_model->j_row(['sku_id' => $item['sku_id']]);
                                    $sku[$k]['album_url'] = $old_sku_row['album_url'];
                                }
                            } else {
                                $sku_num_sn = $sku_row['sku_num_sn'];
                            }

                            $sku[$k]['sku_num_sn'] = $sku_num_sn;
                            $sku[$k]['handle']     = $goods['sku'][$sku_num_sn] ? 'update' : 'insert';
                            $sku[$k]['sku_sn']     = str_replace(' ', '', $item['color']) . '-' . $item['size'];
                            $sku[$k]['sku_id']     = intval($goods['sku'][$sku_num_sn]['sku_id']);
                        }
                    } else {
                        $data['admin_id'] = intval($admin_id);
                        $sku_filter       = ['goods_id' => $goods_id];

                        foreach ($sku as $k => $item) {

                            $sku_filter['color'] = $item['color'];
                            $sku_filter['size']  = $item['size'];

                            $sku_row = $goods_sku_model->j_row($sku_filter);

                            if (empty($sku_row)){
                                if ($item['sku_id']){
                                    $old_sku_row          = $goods_sku_model->j_row(['sku_id' => $item['sku_id']]);
                                    $sku[$k]['album_url'] = $old_sku_row['album_url'];
                                }

                                //新版本sku生成规则
                                /** @var good $good_lib */
                                $good_lib   = get_lib('good');
                                $sku_num_sn = $good_lib->create_sku($data, $item,$data['type_id']);

                                if ( !$sku_num_sn){
                                    $this->sys_message->wrong('sku生成异常!');
                                }
                            } else {
                                $sku_num_sn = $sku_row['sku_num_sn'];
                            }
                            //                        $sku_num_sn = $data['goods_sn'] . $colors['color'][$item['color']]['option_id'] . $colors['color'][$item['color']]['color_on'] . $size['size'][$item['size']]['size_on'];
                            //                        $r = array_filter($sku, function($t) use ($sku_num_sn) { return $t['sku_num_sn'] == $sku_num_sn; });
                            //                        if ($r || !$item['color'] || !$item['size']) {
                            //                            unset($sku[$k]);
                            //                            continue;
                            //                        }
                            $sku[$k]['sku_num_sn'] = $sku_num_sn;
                            $sku[$k]['handle']     = $goods['sku'][$sku_num_sn] ? 'update' : 'insert';
                            $sku[$k]['sku_sn']     = $sku_num_sn;
                            $sku[$k]['sku_id']     = intval($goods['sku'][$sku_num_sn]['sku_id']);
                        }
                    }
                }

                !$sku && $this->sys_message->wrong('请上传SKU!');

                if ($goods){

                    foreach ($goods['sku'] as $row) {
                        $sku_num_sn = $row['sku_num_sn'];
                        $r          = array_filter($sku, function($t) use ($sku_num_sn) {
                            return $t['sku_num_sn'] == $sku_num_sn;
                        });
                        if ( !$r){
                            $sku[] = array(
                                'handle' => 'delete',
                                'sku_id' => $row['sku_id'],
                            );
                        }
                    }
                }
                $data['sku'] = $sku;

                if ($goods['shopify_id'] > 0){

                } else {
                    $files_sort = $this->input->post('files_sort');
                    !$files_sort && $this->sys_message->wrong('请上传图片!');

                    foreach ($files_sort as $k => $val) {

                        if ($val){
                            $sku_img_data = array(
                                'file_name' => $goods['images'][$val]['original_img'],
                                'handle'    => 'update',
                                'album_id'  => $val,
                            );

                            $data['images'][]       = $sku_img_data;
                            $data['images_key'][$k] = $sku_img_data;
                        } else {
                            if ($this->upload->do_upload('files' . $k)){
                                $data_images            = $this->upload->data();
                                $data_images['handle']  = 'insert';
                                $data['images'][]       = $data_images;
                                $data['images_key'][$k] = $data_images;
                            }
                        }
                    }

                    if ($goods){
                        foreach ($goods['images'] as $k => $image) {
                            $album_id = $image['album_id'];
                            $r        = array_filter($data['images'], function($t) use ($album_id) {
                                return $t['album_id'] == $album_id;
                            });
                            if ( !$r){
                                $data['images'][] = array(
                                    'handle'   => 'delete',
                                    'album_id' => $image['album_id'],
                                );
                            }

                        }
                    }
                }

                /*print_r($_FILES);
                print_r($_POST);
                print_r($data['images']);
                print_r($goods['images']);
                exit;*/

                if ($goods['supp'][$data['suppliers_id']]){
                    $data['supp'] = array(
                        'g_supp_id' => $goods['supp'][$data['suppliers_id']]['g_supp_id'],
                        'supp_id'   => $data['suppliers_id'],
                        'cn_name'   => $data['cn_name'],
                        'in_price'  => $data['in_price'],
                        'supp_url'  => $data['supp_url'],
                        'is_host'   => 1,
                    );
                } else {
                    $data['supp'] = array(
                        'supp_id'  => $data['suppliers_id'],
                        'cn_name'  => $data['cn_name'],
                        'in_price' => $data['in_price'],
                        'supp_url' => $data['supp_url'],
                        'is_host'  => 1,
                    );
                }

                //sku图片上传信息
                $data['pro_imgs'] = $_POST['pro_imgs'];

                $goods_id = $this->goods_model->insert_goods($data, $goods_id);


                // $ec_goods_sku = $this->goods_sku_model->e_goods_list($goods_id);


                //foreach ($ec_goods_sku as $row) {
                //$this->eccang->syncProduct($row);
                // }

                $this->sys_message->success('成功!');
            }
            if ($goods){
                foreach ($goods['sku'] as $s_k => $_sku) {
                    if ($_sku['is_delete'] == 1){
                        unset($goods['sku'][$s_k]);
                    }
                }
            }

            //标签
            $this->load->model('Tagslist_model');
            $tags = $this->Tagslist_model->tags_find();
            foreach ($tags as $k => $v) {
                foreach (explode(',', $goods['tags']) as $key => $val) {
                    if ($v['id'] == $val){
                        $tags[$k]['che'] = 1;
                    }
                }
            }

            $data = array(
                'type_option'      => $type_option,
                'suppliers_option' => $suppliers_option,
                'cate_option'      => $cate_option,
                'size_option'      => $size_option,
                'goods_sn'         => $goods_sn,
                'color_option'     => $color_option,
                'admin_name'       => $admin_name,
                'style_setting'    => $this->goods_model->style_setting,
                'goods'            => $goods,
                'admin_id'         => $admin_id,
                'tags'             => $tags,
                'sale_status'      => $sale_status,
            );

            $this->load->view('product_set', $data);
        }

        /**
         *
         * 获取1688商品
         *
         */
        public function ajax_ali_goods()
        {

            $this->load->library('ali');

            $url = $this->input->post('ali_url');
            //------孙坚 开始 ----- //
            $supp_id = $this->input->post('supp_id');

            //查看是否有保存数据
            $this->load->model('suppliers_model');
            $info = $this->suppliers_model->goods_supp_info(array('supp_url' => strstr($url, '?', true)));
            if ( !$info){
                //数据不存在去ali查询数据
                $info               = $this->ali->pu_goods($url);
                $url                = strstr($url, '?', true);
                $data['supp_url']   = $url;    //产品链接
                $data['supp_id']    = $supp_id; //供应商ID
                $data['goods_json'] = json_encode($info); //商品数据
                $this->db->insert("goods_supp", $data);
            } else {
                $info = json_decode($info['goods_json'], true);
            }
            //-----孙坚 结束-------- //

            $_ali_goods = $info['data'];

            $ali_goods = array();

            $ali_price = explode('-', $_ali_goods['displayPrice']);
            $skuProps  = $_ali_goods['skuProps'];

            $attributes = array();
            foreach ($_ali_goods['attributes'] as $row) {
                $row                 = explode(':', $row);
                $attributes[$row[0]] = $row[1];
            }

            $re_ali_goods = array(
                'ali_price' => $ali_price[0],
                'ali_sn'    => $attributes['货号'],
                'skuProps'  => $skuProps,
            );

            echo json_encode($re_ali_goods);
            exit;
        }

        public function scv_set()
        {

            $this->load->model('goods_model');

            if ($_FILES){

            }

            $sum = $this->input->post('sum') ? $this->input->post('sum') : 100;

            $data = "goods_sn,goods_title,goods_cn_title,cate_name,type,supp_name,supp_sn,supp_url,goods_weight,in_price,market_price,shop_price,sku_size,sku_color,img_count,body_html \n";


            for ($i = 0; $i <= $sum; $i++) {
                $goods_sn = $this->goods_model->build_goods_sn(0, '', $i + $_SESSION['admin_id']);
                $data     .= "{$goods_sn},,,,,,,,,,,,,, \n";
            }

            $filename = 'export_goods-' . date('YmdHis', time()) . '.csv';
            header("Content-type:text/csv");
            header("Content-Disposition: attachment; filename=$filename");
            echo $data;
            exit;
        }

        public function scv_up()
        {

            $config = array(
                'upload_path'   => './album/',
                'allowed_types' => 'csv',
                'max_size'      => '1000000000',
            );

            $this->load->library('upload', $config);
            $this->load->model('category_model');
            $this->load->model('goods_model');
            $this->load->model('suppliers_model');
            $this->load->model('size_model');
            $this->load->model('color_model');

            $size   = $this->size_model->size_option();
            $colors = $this->color_model->color_option();

            if ( !$this->upload->do_upload('fileUpload')){

            } else {
                $data = array('upload_data' => $this->upload->data());

                $d = $this->ReadCsv($data['upload_data']['full_path']);

                unset($d[0]);

                foreach ($d as $k => $row) {

                    $cate_id = $this->category_model->ls_cate_id($row[3]);
                    $type_id = $this->goods_model->get_type_id($row[4]);
                    $supp_id = $this->suppliers_model->get_supp_id($row[5]);

                    $_data = array(
                        'goods_sn'     => trim($row[0]),
                        'goods_name'   => trim($row[1]),
                        'cn_name'      => trim($row[2]),
                        'cat_id'       => intval($cate_id),
                        'type_id'      => intval($type_id),
                        'suppliers_id' => intval($supp_id),
                        'supp_sn'      => trim($row[6]),
                        'supp_url'     => trim($row[7]),
                        'goods_weight' => trim($row[8]),
                        'in_price'     => trim($row[9]),
                        'market_price' => trim($row[10]),
                        'shop_price'   => trim($row[11]),
                        'body_html'    => trim($row[15]),
                    );

                    $data = array_filter($_data);

                    if (count($data) < 5){
                        continue;
                    }

                    $goods_id = $this->goods_model->goods_id(0, array('goods_sn' => $data['goods_sn']));

                    if ($goods_id){
                        continue;
                    }

                    $data['market_price'] = 0;

                    $_sku['size']  = explode(',', $row['12']);
                    $_sku['color'] = explode(',', $row['13']);

                    $sku = array();
                    foreach ($_sku['size'] as $key => $item) {
                        foreach ($_sku['color'] as $_yk => $val) {
                            $sku[$key . $_yk] = array(
                                'size'  => $item,
                                'color' => $val,
                            );
                        }
                    }

                    foreach ($sku as $_sk => $item) {

                        $color_num = $this->color_model->get_color_num($item['color']);

                        $sku_num_sn = preg_replace("/[a-zA-Z]/", "", $data['goods_sn']) . $color_num . $size['size'][$item['size']]['size_num'];

                        $r = array_filter($sku, function($t) use ($sku_num_sn) {
                            return $t['sku_num_sn'] == $sku_num_sn;
                        });
                        if ($r || !$item['color'] || !$item['size']){
                            unset($sku[$_sk]);
                            continue;
                        }

                        $sku[$_sk]['sku_num_sn'] = $sku_num_sn;
                        $sku[$_sk]['handle']     = 'insert';
                        $sku[$_sk]['sku_sn']     = str_replace(' ', '', $item['color']) . '-' . $item['size'];
                        $sku[$_sk]['sku_id']     = 0;
                    }

                    $data['sku'] = $sku;

                    $j              = 1;
                    $data['images'] = array();
                    while ($j <= $row[14]) {
                        $data['images'][] = array(
                            'file_name' => "/album/{$data['goods_sn']}/{$j}.jpg",
                            'handle'    => 'insert',
                        );
                        $j++;
                    }

                    $data['supp'] = array(
                        'supp_id'  => $data['suppliers_id'],
                        'cn_name'  => $data['cn_name'],
                        'in_price' => $data['in_price'],
                        'supp_url' => $data['supp_url'],
                        'is_host'  => 1,
                    );

                    $goods_id = $this->goods_model->insert_goods($data);
                }

                print_r($d);
                exit;
            }

            $this->load->view('product_scv_up');
        }

        public function ReadCsv($uploadfile = '')
        {
            $file = fopen($uploadfile, "r");
            while ( !feof($file)) {
                $data[] = fgetcsv($file);
            }
            $data = eval('return ' . iconv('gbk', 'utf-8', var_export($data, true)) . ';');
            foreach ($data as $key => $value) {
                if ( !$value){
                    unset($data[$key]);
                }
            }
            fclose($file);
            return $data;
        }


        public function add_supp_list()
        {

            $this->load->model('goods_model');
            $this->load->model('goods_sku_model');
            $this->load->model('goods_type_model');
            $this->load->model('suppliers_model');

            $assoc = $this->uri->uri_to_assoc();
            $this->load->helper(array('form', 'url'));
            $this->load->library('form_validation');


            if ($_POST){
                foreach ($_POST as $k => $row) {

                    if ( !$k || !$row['supp_url']){
                        continue;
                    }

                    $data = array(
                        'goods_id' => intval($k),
                        'supp_id'  => intval($row['supp_id']),
                        'type_id'  => strval($row['type_id']),
                        'in_price' => $row['in_price'],
                        'is_host'  => 1,
                        'supp_url' => $row['supp_url'],
                    );

                    $this->goods_model->up_goods_supp_info($data);
                }
                redirect(base_url('product/add_supp_list'));
            }

            $_param_option = array(
                'goods_name' => array(
                    'col'         => 'col-lg-3',
                    'type'        => 'text',
                    'placeholder' => '输入产品名称、货号',
                ),
            );

            $_param     = array(
                'goods_name' => $this->input->get('goods_name'),
            );
            $show_param = $_param;

            $goods_sku = $this->goods_sku_model->sku_info(array('sku_num_sn' => $_param['goods_name']));
            if ($goods_sku['goods_sn']){
                $_param['goods_name'] = $goods_sku['goods_sn'];
            }

            $_param['is_supp'] = 1;

            $goods_list = $this->goods_model->goods_list($_param);

            $suppliers_option = $this->suppliers_model->suppliers_option();
            $type_option      = $this->goods_type_model->type_option();

            $suppliers_option_str = '';
            foreach ($suppliers_option as $k => $val) {
                $suppliers_option_str .= '<option value="' . $k . '">' . $val . '</option>';
            }

            $type_option_str = '';
            foreach ($type_option as $k => $val) {
                $type_option_str .= '<option value="' . $k . '">' . $val . '</option>';
            }

            $data = array(
                'goods_list'           => $goods_list,
                'suppliers_option_str' => $suppliers_option_str,
                'type_option_str'      => $type_option_str,
                'param_option'         => $_param_option,
                'param'                => $show_param,
            );

            $this->load->view('goods_add_supp_list', $data);
        }


        public function export_csv()
        {

            $export_goods = $_COOKIE['export_goods'];

            $this->load->model('goods_sku_model');
            $this->load->model('goods_model');
            $this->load->model('shopify_goods_model');
            $this->load->model('siteweb_model');

            $assoc = $this->uri->uri_to_assoc();

            $siteweb = $this->siteweb_model->siteweb_info(array('web_name' => $assoc['web_name']));

            $site = $siteweb['title'];

            $goods_list = $this->goods_sku_model->goods_sku_ex($export_goods);

            $data = "Handle,Title,Body (HTML),Vendor,Type,Tags,Published,Option1 Name,Option1 Value,Option2 Name,Option2 Value,Option3 Name,Option3 Value,Variant SKU,Variant Grams,Variant Inventory Tracker,Variant Inventory Qty,Variant Inventory Policy,Variant Fulfillment Service,Variant Price,Variant Compare At Price,Variant Requires Shipping,Variant Taxable,Variant Barcode,Image Src,Image Alt Text,Gift Card,Google Shopping / MPN,Google Shopping / Age Group,Google Shopping / Gender,Google Shopping / Google Product Category,SEO Title,SEO Description,Google Shopping / AdWords Grouping,Google Shopping / AdWords Labels,Google Shopping / Condition,Google Shopping / Custom Product,Google Shopping / Custom Label 0,Google Shopping / Custom Label 1,Google Shopping / Custom Label 2,Google Shopping / Custom Label 3,Google Shopping / Custom Label 4,Variant Image,Variant Weight Uni
";
            foreach ($goods_list as $row) {

                $shopify_goods = $this->shopify_goods_model->goods_info(array('goods_id' => $row['goods_id'], 'web_id' => $siteweb['web_id']));

                if ( !$shopify_goods){
                    $goods_sku = $this->goods_model->get_goods_sku($row['goods_id']);
                    $variants  = array();
                    foreach ($goods_sku as $row1) {
                        $variants[] = array(
                            'option1' => $row1['size'],
                            'option2' => $row1['color'],
                            'sku'     => $siteweb['ab_name'] . $row1['sku_num_sn'],
                            'price'   => $row['shop_price'],
                        );
                    }

                    $data_array = array(
                        'goods_id'     => $row['goods_id'],
                        'goods_sn'     => $siteweb['ab_name'] . preg_replace("/[a-zA-Z]/", "", $row['goods_sn']),
                        'web_id'       => $siteweb['web_id'],
                        'goods_name'   => "{$siteweb['title']} " . $row['goods_name'],
                        'cat_id'       => $row['cat_id'],
                        'shop_price'   => $row['shop_price'],
                        'market_price' => $row['market_price'],
                        'body_html'    => $row['body_html'],
                        'is_sales'     => 1,
                        'variants'     => $variants,
                        'tags'         => '',
                    );

                    $sg_id = $this->shopify_goods_model->insert_goods($data_array);
                }

                $handle = str_replace(' ', '-', trim($row['goods_name']));

                if (strpos($row['original_img'], 'https://') !== false){
                } else {
                    $row['original_img'] = $this->imgToBase64($row['original_img']);
                }


                $images = array();
                /*foreach ($row['images'] as $image) {
                    if (strpos($row['original_img'],'https://') !== false) {
                        $images[] = $image['original_img'];
                    } else {
                        $images[] = $this->imgToBase64($image['original_img']);
                    }

                }*/

                $data .= "$site-$handle,$site {$row['goods_name']},\"" . str_replace('"', '""', $row['body_html']) . "\",,,,TRUE," . ($row['size'] ? "Size,{$row['size']}," : ',,') .
                         ($row['color'] ? "Color,{$row['color']}," : ",,") . ",,{$siteweb['ab_name']}{$row['sku_num_sn']},{$row['goods_weight']},,9999,deny,manual,{$row['shop_price']},,TRUE,TRUE,,"
                         . "http://cdn.shopify.com/s/images/shopify_shirt.png?e6948ca4d9028f9e734b8202cc472e3b89aae0f3,$site {$row['goods_name']},FALSE,,,1604,female,,{$siteweb['ab_name']}{$row['sku_num_sn']}"
                         . ",,,new,,,,,,,,Kg
";
            }
            $filename = 'export_goods-' . date('YmdHis', time()) . '.csv';
            header("Content-type:text/csv; charset=utf-8");
            header("Content-Disposition: attachment; filename=$filename");
            echo $data;
            exit;
        }

        function imgToBase64($img_file)
        {

            $img_base64 = '';
            if (file_exists($_SERVER['DOCUMENT_ROOT'] . $img_file)){
                $app_img_file = $_SERVER['DOCUMENT_ROOT'] . $img_file;

                //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
                $fp = fopen($app_img_file, "r");

                if ($fp){
                    $filesize   = filesize($app_img_file);
                    $content    = fread($fp, $filesize);
                    $img_base64 = chunk_split(base64_encode($content));

                }
                fclose($fp);
            }

            return $img_base64;
        }

        public function export()
        {
            $this->load->model('goods_model');
            $this->load->model('siteweb_model');


            if ($_POST){

                $param   = array(
                    'web_id' => intval($this->input->post('web_id')),
                );
                $siteweb = $this->siteweb_model->siteweb_info($param);

                $param['order_start'] = strtotime(trim($this->input->post('order_start')));
                $param['order_end']   = strtotime(trim($this->input->post('order_end')));

                $this->load->library('shopify_api', $siteweb);

                $handle_type = intval($this->input->post('handle_type'));

                switch ($handle_type) {
                    case 1:

                        $goods_list = $this->goods_model->goods_list($param, 1);

                        $site_url = "https://www.{$siteweb['web_name']}.com/products/";


                        $data = "id,title,description,availability,condition,price,link,image_link,brand,additional_image_link,age_group,color,gender,item_group_id,google_product_category,material,pattern,product_type,sale_price,sale_price_effective_date,shipping,shipping_weight,size,custom_label_0,custom_label_1,custom_label_2,custom_label_3,custom_label_4\n";

                        foreach ($goods_list as $row) {
                            $_variants = unserialize($row['variants']);
                            $_images   = unserialize($row['images']);


                            if ($_images){
                                $_image        = array_shift($_images);
                                $_image['src'] = preg_replace("/\?v=[0-9]+/i", '', $_image['src']);
                                $img           = preg_replace("/\?v=[0-9]+/i", '', implode(',', array_column($_images, 'src')));
                            }

                            $sg_body_html = str_replace(array(PHP_EOL, '"', "'"), ' ', preg_replace("/<.*?>/i", '', $row['sg_body_html']));


                            if ($_variants){
                                foreach ($_variants as $variant) {
                                    $link = $site_url . $row['goods_url'] . "?variant={$variant['id']}";
                                    $data .= "{$variant['sku']},\"{$row['sg_name']}\",\"{$sg_body_html}\",in stock,new,{$row['shop_price']} USD,{$link},{$_image['src']},{$siteweb['web_name']},\"{$img}\",adult,{$variant['option2']},unisex,,\"Apparel & Accessories > Clothing\",,,{$row['cate_name']},,,,,{$variant['option1']},,,,,\n";
                                }
                            }
                        }

                        break;
                    case 2:

                        $goods_list = $this->goods_model->sales_goods($param);

                        $data = "序列,图片,产品状态,产品来源,是否看样,供应商产能,备货详情,是否受到投诉,上架时间,在售时间,分类,售价,货号,颜色\n";

                        foreach ($goods_list as $row) {
                            $add_date = date('Y-m-d', $row['add_time']);
                            $data     .= "{$row['goods_id']},,,,,,,,{$add_date},,{$row['cate_name']},{$row['shop_price']},{$row['goods_sn']},{$row['color']}\n";

                        }

                        break;
                    case 3:

                        $this->load->model('order_goods_model');

                        $start = date('Y-m-d', $param['order_start']);
                        $end   = date('Y-m-d', $param['order_end']);
                        $data  = "序列,颜色,销量（{$start} - {$end}）\n";

                        $goods_list = $this->goods_model->sales_goods($param);

                        $order_goods_list = $this->order_goods_model->get_order_goods_sales_list($param);


                        foreach ($goods_list as $row) {

                            $sale_num = intval($order_goods_list["{$row['goods_id']}-{$row['color']}"]['goods_number']);

                            $data .= "{$row['goods_id']},{$row['color']},{$sale_num}\n";
                        }

                        break;
                }

                $file_name = date('YmdHis', time()) . '.csv';
                header('Content-Type: application/download');
                header("Content-type:text/csv;");
                header("Content-Disposition:attachment;filename=" . $file_name);
                header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
                header('Expires:0');
                header('Pragma:public');
                echo $data;
                exit;

            }

            $data = array(
                'siteweb' => $this->siteweb_model->siteweb_option(),
            );

            $this->load->view('purchase_export', $data);
        }

        public function get_goods_sn()
        {

            $this->load->library('session');

            $this->load->model('goods_model');

            $i_admin_id = intval($this->input->post('admin_id'));

            $admin_id = intval($i_admin_id ? $i_admin_id : $_SESSION['admin_id']);

            $goods_sn = $this->goods_model->goods_sn_max($admin_id);

            $this->session->set_userdata('admin_id', $admin_id);


            echo $goods_sn;
            exit;
        }

        public function excel()
        {
            ini_set('memory_limit', '800M');
            $this->load->model('goods_model');
            //$this->load->model('order_model');
            $this->load->model('tagslist_model');
            $_param      = array(
                'goods_name'     => trim($this->input->get('goods_name')),
                'cate_name'      => intval($this->input->get('cate_name')),
                'admin_id'       => intval($this->input->get('admin_id')),
                'is_on_sale'     => intval($this->input->get('is_on_sale')),
                'is_on_sales'    => intval($this->input->get('is_on_sales')),
                'siteweb'        => intval($this->input->get('siteweb')),
                'add_time_start' => trim($this->input->get('add_time_start')),
                'add_time_end'   => trim($this->input->get('add_time_end')),
                'is_tort'        => trim($this->input->get('is_tort')),
            );
            $excel_psge  = !$this->input->get('excel_psge') ? $excel_psge = 1 : $this->input->get('excel_psge');
            $_goods_list = $this->goods_model->goods_list($_param, 99, $excel_psge);

            foreach ($_goods_list as $key => $row) {
                // $_goods_list[$key]['goods_num'] = $this->order_model->order_goods_num($row['shopify_id']);
                $webs                      = [];
                $tagslist                  = $this->tagslist_model->tags_in($row['tags']);
                $_goods_list[$key]['tags'] = $tagslist;
                if ( !empty($row['wou'])){
                    foreach ($row['wou'] as $k => $v) {
                        $webs [] = $v['web_name'];
                    }

                    $webs                      = implode(',', $webs);
                    $_goods_list[$key]['webs'] = $webs;
                } else {
                    $_goods_list[$key]['webs'] = '';
                }


            }
            $this->load->library('PHPExcel');
            $objPHPExcel = new \PHPExcel ();
            // Set document properties
            $objPHPExcel->getProperties()->setCreator("zend")-> // 作者
            setLastModifiedBy("zend")-> // 最后一次保存者
            setTitle("Office 2007 XLSX Document")-> // 标题
            setSubject("Office 2007 XLSX Document")-> // 主题
            setDescription("document for Office 2007 XLSX, generated using PHP classes.")-> // 备注
            setKeywords("office 2007 openxml php")-> // 标记
            setCategory("result file"); // 类别

            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth('15'); // 设置列宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth('30');
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth('30');
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth('20');

            // Add some data
            $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A1', 'id') // 第一行A列值
                        ->setCellValue('B1', '商品名称') // 第一行B列值
                        ->setCellValue('C1', '图片') // 第一行C列值
                        ->setCellValue('D1', '货号') // 第一行D列值
                        ->setCellValue('E1', '供应商')
                        ->setCellValue('F1', '站点')
                        ->setCellValue('G1', '进货价')
                        ->setCellValue('H1', '价格')
                        ->setCellValue('I1', '重量')
                        ->setCellValue('J1', '质检')
                        ->setCellValue('K1', '侵权')
                        ->setCellValue('L1', '是否下架')
                        ->setCellValue('M1', '链接');

            foreach ($_goods_list as $k => $v) {
                $supp_url = $this->db->from('goods_supp')->where(['goods_id'=>$v['goods_id']])->select('supp_url')->get()->row_array();
                if ($v['is_testing'] == 1){
                    $is_testing = '合格';
                } elseif ($v['is_testing'] == 2) {
                    $is_testing = '不合格';
                } else {
                    $is_testing = '待质检';
                }
                $is_tort    = $v['is_tort'] == 1 ? '侵权' : '不侵权';
                $is_on_sale = $v['is_on_sale'] == 1 ? '上架' : '下架';
                // 从此开始行数可在循环中累加
                $objPHPExcel->setActiveSheetIndex(0)
                            ->setCellValue('A' . ($k + 2), ' ' . $v['goods_id']) // 第二行A列值
                            ->setCellValue('B' . ($k + 2), ' ' . $v['goods_name']); // 第二行B列值

                /* 实例化插入图片类 */
                $objDrawing = new \PHPExcel_Worksheet_Drawing ();
                /* 设置图片路径 切记：只能是本地图片 D:\phpstudy\PHPTutorial\WWW\application\controllers\1.jpg*/
                $img             = substr($v['original_img'], 1);
                $_is_shopify_img = strstr($img, 'cdn.shopify.com');
                if ($_is_shopify_img){
                    $objDrawing->setPath('album/2019/05/shopify/bucunzai.jpg');
                } else {
                    $objDrawing->setPath($img);
                }
                //$objDrawing->setPath ( '/s/files/1/2372/5739/products/201708_D_1502956242_20659.jpg?v=1507198258' );
                /* 设置图片高度 */
                $objDrawing->setHeight(100);
                /* 设置图片要插入的单元格位置 */
                $objDrawing->setCoordinates('C' . ($k + 2)); // 这里第二行C列
                // 写入图片在指定格中的X坐标值
                $objDrawing->setOffsetX(20);
                // 写入图片在指定格中的Y坐标值
                $objDrawing->setOffsetY(20);
                // 设置旋转角度
                // $objDrawing->setRotation(20);
                $objDrawing->getShadow()->setVisible(true);
                $objDrawing->getShadow()->setDirection(50);
                $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());

                // // 设置单元格高度
                // $objPHPExcel->getActiveSheet()->getRowDimension($k + 2)->setRowHeight(100);

                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . ($k + 2), ' ' . $v['goods_sn']) // 第二行D列值
                            ->setCellValue('E' . ($k + 2), ' ' . $v['suppliers_name'])
                            ->setCellValue('F' . ($k + 2), ' ' . $v['webs'])
                            ->setCellValue('G' . ($k + 2), ' ' . $v['in_price'])
                            ->setCellValue('H' . ($k + 2), ' ' . $v['shop_price'])
                            ->setCellValue('I' . ($k + 2), ' ' . $v['goods_weight'])
                            ->setCellValue('J' . ($k + 2), ' ' . $is_testing)//质检
                            ->setCellValue('K' . ($k + 2), ' ' . $is_tort)//侵权
                            ->setCellValue('L' . ($k + 2), ' ' . $is_on_sale)//下架
                            ->setCellValue('M' . ($k + 2), ' ' . $supp_url['supp_url']);
            }

            $objPHPExcel->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);
            $objPHPExcel->getActiveSheet()->getPageSetup()->setVerticalCentered(false);
            ob_end_clean();
            ob_start();
            $file_name = date('Y-m-d_His') . '.xls';
            header('Content-Disposition: attachment;filename=' . $file_name);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;

        }

        /**
         *
         * 商品下架
         *
         */

        public function off_shelve_list()
        {
            $this->load->model('goods_sku_model');
            $this->load->model('shopify_goods_model');
            $this->load->model('goods_model');
            $this->load->model('order_model');
            $this->load->model('category_model');
            $this->load->model('siteweb_model');
            $this->load->model('admin_model');

            $this->load->library('pagination');

            $assoc = $this->uri->uri_to_assoc();

            $_param_option = array(
                'goods_name' => array(
                    'col'         => 'col-lg-3',
                    'type'        => 'text',
                    'placeholder' => '输入产品名称、货号',
                ),
                'add_time'   => array(
                    'col'         => 'col-lg-4',
                    'type'        => 'dpd_time',
                    'placeholder' => '下架时间',
                ),
            );

            $_param = array(
                'goods_name'     => trim($this->input->get('goods_name')),
                'add_time_start' => trim($this->input->get('add_time_start')),
                'add_time_end'   => trim($this->input->get('add_time_end')),
                'page'           => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0,
            );

            $config['base_url']         = base_url('Product/') . 'off_shelve_list/page/';
            $config['total_rows']       = $this->goods_model->goods_num($_param);
            $config['num_links']        = 6;
            $config['per_page']         = $this->goods_model->limit_rows;
            $config['use_page_numbers'] = true;
            $this->pagination->initialize($config);

            $_goods_list = $this->goods_model->goods_list($_param);

            foreach ($_goods_list as $k => $v) {
                $_goods_list[$k]['sku'] = $this->goods_sku_model->goods_sku_select($v['goods_id']);
                $_goods_list[$k]['web'] = $this->shopify_goods_model->get_goods_siteweb_list($v['goods_id']);
            }
            $data = array(
                'param_option' => $_param_option,
                'goods_list'   => $_goods_list,
                'pages'        => $this->pagination->create_links(),
                'param'        => $_param,
            );

            $this->load->view('off_shelve', $data);
        }

        public function off_shelve()
        {
            $this->load->model('goods_model');
            $this->load->model('goods_sku_model');
            $this->load->model('shopify_goods_model');

            $this->load->library('sys_message');
            $this->load->library('eccang');
            $this->load->library('shopify_api');

            $assoc = $this->uri->uri_to_assoc();


            $goods_id = intval($assoc['goods_id'] ? $assoc['goods_id'] : $this->input->post('goods_id'));

            $goods = $this->goods_model->goods_info($goods_id);

            !$goods && $this->sys_message->warning('产品不存在！');
            $goods['is_on_sale'] == 0 && $this->sys_message->warning('产品已经下架！');

            $sku_list = $this->goods_sku_model->goods_sku_select($goods_id);
            $web_list = $this->shopify_goods_model->get_goods_siteweb_list($goods_id);

            $_sku_list = array_filter($sku_list, function($val) {
                return $val['is_on_sale'] == 1;
            });

            if ($_POST){

                $data = array(
                    'sku_ids' => array_filter($this->input->post('sku')),
                    //'web_ids' => array_filter($this->input->post('web')),
                );
                //count($data['web_ids']) <= 0 && $this->sys_message->warning('未选中站点，无法下架！');
                count($data['sku_ids']) <= 0 && $this->sys_message->warning('未选中sku，无法下架！');

                //易仓下架
                foreach ($data['sku_ids'] as $sku_id) {
                    $goods_type = $this->db->from('goods_type')->where(['cat_id' => $goods['type_id']])->get()->row_array();
                    $_sku_ids[] = $this->eccang->syncProduct_edit($sku_list[$sku_id]['sku_sn'], $goods_type['cat_name_zh'], $goods_type['cat_name'], 1);
                }

                //shopify下架
                if (count($_sku_list) > count($data['sku_ids'])){ //部分下架

                    $from_sku = $data['sku_ids'];
                    $data_sku = array_filter($sku_list, function($val) use ($from_sku) {
                        return !in_array($val['sku_id'], $from_sku);
                    });

                    foreach ($web_list as $web) {

                        $variants = array();
                        foreach ($data_sku as $sku) {
                            $variants[] = array(
                                'option1' => $sku['size'],
                                'option2' => $sku['color'],
                                'sku'     => $web['ab_name'] . $sku['sku_num_sn'],
                                'price'   => $goods['shop_price'],
                            );
                        }

                        $this->shopify_api->initialize($web);
                        $this->shopify_api->published_sku($web['shopify_id'], $variants);
                    }

                    $is_on_sale = 2;
                } else { //整个下架
                    foreach ($web_list as $web) {

                        //删除商品
                        $this->shopify_api->initialize($web);
                        $this->shopify_api->goods_delete($web['shopify_id']);
                    }

                    $is_on_sale = 0;
                }

                //erp下架
                $this->goods_model->is_on_sale(array(
                                                   'is_on_sale' => $is_on_sale,
                                                   'goods_id'   => $goods_id,
                                                   'sku_ids'    => $data['sku_ids'],
                                                   'web_ids'    => array_column($web_list, 'web_id'),
                                                   'reason'     => $this->input->post('reason'),
                                                   'on_sale'    => 0,
                                               ));

                $this->sys_message->success('成功！');
            }

            $data = array(
                'sku_list' => $_sku_list,
                'web_list' => $web_list,
            );

            $this->sys_message->success('成功！', $data);
        }

        public function outstock()
        {
            $this->load->model('goods_model');
            $this->load->model('goods_sku_model');
            $this->load->model('epurchase_orders_model');

            $_param = array(
                'goods_name'     => trim($this->input->get('goods_name')),
                'cate_name'      => intval($this->input->get('cate_name')),
                'is_on_sale'     => intval($this->input->get('is_on_sale')),
                'siteweb'        => intval($this->input->get('siteweb')),
                'add_time_start' => trim($this->input->get('add_time_start')),
                'add_time_end'   => trim($this->input->get('add_time_end')),
            );

            $sg_g_count = $this->epurchase_orders_model->salse_goods_count($_param);
            $pg_g_count = $this->epurchase_orders_model->pg_count($_param);

            $supp_count = array();

            if ($_param['add_time_start']){
                $_param['count'] = 1;
                $sg_count        = $this->epurchase_orders_model->salse_goods_count($_param);


                $supp = array();
                foreach ($sg_count as $goods) {
                    $supp[$goods['suppliers_id']] = $goods['goods_count'];
                }

                $_param['supp_id'] = array_keys($supp);
                $pg_count          = $this->epurchase_orders_model->pg_count($_param);


                foreach ($pg_count as $count) {
                    $supp_count[$count['suppliers_id']] = array(
                        'count'     => sprintf('%.2f', $supp[$count['suppliers_id']] / $count['goods_count'] * 100) . '%',
                        'supp_name' => $count['suppliers_name'],
                    );
                }
            }


            $data = array(
                'supp_count' => $supp_count,
                'sg_g_count' => $sg_g_count,
                'pg_g_count' => $pg_g_count,
            );

            $this->load->view('library/out_stock', $data);
        }


        public function open_shelve()
        {

            $this->load->model('goods_model');
            $this->load->model('goods_sku_model');
            $this->load->model('shopify_goods_model');

            $this->load->library('sys_message');
            $this->load->library('eccang');
            $this->load->library('shopify_api');

            $assoc = $this->uri->uri_to_assoc();

            $goods_id = intval($assoc['goods_id'] ? $assoc['goods_id'] : $this->input->post('goods_id'));

            $goods = $this->goods_model->goods_info($goods_id);

            !$goods && $this->sys_message->warning('产品不存在！');

            $sku_list = $this->goods_sku_model->goods_sku_select($goods_id);
            $web_list = $this->shopify_goods_model->get_goods_siteweb_list($goods_id);

            if ($_POST){

                $data = array(
                    'sku' => array_filter($this->input->post('sku')),
                    'web' => array_filter($this->input->post('web')),
                );
                count($data['web']) <= 0 && $this->sys_message->warning('未选中站点，无法下架！');
                count($data['sku']) <= 0 && $this->sys_message->warning('未选中sku，无法下架！');


                //易仓上架
                foreach ($data['sku'] as $sku_id) {
                    $_sku_ids[] = $this->eccang->syncProduct_edit($sku_list[$sku_id]['sku_sn'], 2);
                }
                foreach ($web_list as $web) {
                    //重新上传商品
                    if ($web['is_sales'] == 0){
                        $goods_id = $this->input->post('goods_id');
                        $sg_id    = $this->db->from('shopify_goods')->select('sg_id')
                                             ->where(['goods_id' => $goods_id, 'web_id' => $web['web_id']])
                                             ->get()->row_array();

                        $this->shopify_api->initialize($web);
                        $shopify_data = $this->shopify_goods_model->up_shopify_data($sg_id['sg_id']);
                        $sku_num_sn   = $this->db->from('goods_sku')
                                                 ->select('sku_num_sn,size,color')
                                                 ->where_in('sku_id', $data['sku'])->get()->result_array();
                        foreach ($sku_num_sn as $key => $value) {
                            $sku_num_sn[$key]['option1'] = $value['size'];
                            $sku_num_sn[$key]['option2'] = $value['color'];
                            $sku_num_sn[$key]['sku']     = $web['ab_name'] . $value['sku_num_sn'];
                            $sku_num_sn[$key]['price']   = $shopify_data['shop_price'];
                            unset($sku_num_sn[$key]['sku_num_sn']);
                            unset($sku_num_sn[$key]['size']);
                            unset($sku_num_sn[$key]['color']);
                        }
                        $shopify_data['variants'] = $sku_num_sn;


                        $response = $this->shopify_api->upload_goods($shopify_data);
                        if ($response){
                            $shopify_goods_data = array(
                                'shopify_id'  => $response['id'],
                                'update_time' => 0,
                            );
                            $this->shopify_goods_model->update_goods($sg_id['sg_id'], $shopify_goods_data);
                        }
                        //修改站点上架
                        $this->shopify_goods_model->update_web($data['web'], 1);
                    } else {
                        //上架shopify
                        $variants = array();
                        if (in_array($web['sg_id'], $data['web'])){
                            foreach ($data['sku'] as $sku) {
                                $variants[] = array(
                                    'option1' => $sku_list[$sku]['size'],
                                    'option2' => $sku_list[$sku]['color'],
                                    'sku'     => $web['ab_name'] . $sku_list[$sku]['sku_sn'],
                                    'price'   => $goods['shop_price'],
                                );
                            }
                            $this->shopify_api->initialize($web);
                            $shopify_goods = $this->shopify_api->published_sku($web['shopify_id'], $variants);

                            if ($shopify_goods){
                                $this->shopify_goods_model->update_goods($web['sg_id'], array(
                                    'is_sales' => 1,
                                ));
                            }
                        }
                    }
                }

                //上下架加日志操作
                foreach ($data['sku'] as $v) {
                    $arr['sku_id']   = $v;
                    $arr['admin_id'] = $_SESSION['admin_id'];
                    $arr['add_time'] = time();
                    $arr['reason']   = $this->input->post('reason');
                    $arr['is_type']  = 2;
                    $this->goods_sku_model->shelf_log($arr);
                }


                //修改SUK
                $this->goods_sku_model->update($data['sku'], array(
                    'is_on_sale' => 1,
                ));

                //修改goods 2部分上架 1全部上架
                if (count($sku_list) > count($data['sku'])){
                    $is_on_sale = 2;
                } else {
                    $is_on_sale = 1;
                }
                $this->goods_model->update_goods($goods_id, array(
                    'is_on_sale' => $is_on_sale,
                ));
                $this->sys_message->success('成功！');
            }


            $data = array(
                'sku_list' => $sku_list,
                'web_list' => $web_list,
            );

            $this->sys_message->success('成功！', $data);

        }

        public function goods_color()
        {
            $goods_id = $this->input->post('goods_id');
            $this->load->model('goods_model');
            $res = $this->goods_model->goods_color($goods_id);
            echo json_encode($res);
        }

        public function update_color()
        {
            $this->load->library('sys_message');
            $val = $this->input->post('arr');
            foreach ($val as $k => $v) {
                $this->db->where(['goods_id' => $v['goods_id'], 'color' => $v['color']])->update('goods_sku', ['sort' => $v['sort']]);
            }
            $this->sys_message->success('成功！', $data);
        }

        public function user_list()
        {
            $this->load->model('siteweb_model');
            $siteweb = $this->siteweb_model->siteweb_option();

            $_param_option = array(
                'email'   => array(
                    'col'         => 'col-lg-3',
                    'type'        => 'text',
                    'placeholder' => '邮箱',
                ),
                'siteweb' => array(
                    'col'         => 'col-lg-2',
                    'type'        => 'option',
                    'placeholder' => '请选择网站',
                    'option'      => $siteweb,
                ),
            );


            $this->load->model('goods_model');
            $this->load->library('pagination');
            $assoc = $this->uri->uri_to_assoc();

            $_param = array(
                'email'   => trim($this->input->get('email')),
                'siteweb' => trim($this->input->get('siteweb')),
                'page'    => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0,
            );


            $config['base_url']         = base_url('Product/') . 'user_list/page/';
            $config['total_rows']       = $this->db->from('customer')->count_all_results();
            $config['num_links']        = 6;
            $config['per_page']         = $this->goods_model->limit_rows;
            $config['use_page_numbers'] = true;
            $this->pagination->initialize($config);

            $user_list = $this->goods_model->user_list($_param);


            $data = array(
                'param_option' => $_param_option,
                'user_list'    => $user_list,
                'param'        => $_param,
                'pages'        => $this->pagination->create_links(),
            );
            $this->load->view('user_list', $data);
        }

        public function shopify_goods_delete()
        {
            $this->load->library('sys_message');
            $web_id   = $this->input->post('web_id');
            $goods_id = $this->input->post('goods_id');
            if ( !$web_id || !$goods_id){
                $this->sys_message->wrong('删除失败!');
            }
            $res = $this->db->delete('shopify_goods', ['web_id' => $web_id, 'goods_id' => $goods_id]);
            if ($res){
                $this->sys_message->success('成功！');
            } else {
                $this->sys_message->wrong('删除失败!');
            }

        }

        public function search_map()
        {
            if ($_FILES){
                $config['upload_path']   = './album';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size']      = 1000;
                $config['max_width']     = 1024;
                $config['max_height']    = 768;
                $this->load->library('upload', $config);
                if ( !$this->upload->do_upload('file_pcs')){
                    $error = array('error' => $this->upload->display_errors());
                    print_r($error);
                    die;
                } else {
                    $data = $this->upload->data();
                    $this->load->library('Soutu');
                    $goods_album = $this->db->from('goods_album')->get()->result_array();
                    foreach ($goods_album as $key => $value) {
                        if ( !is_file(substr($value['original_img'], 1))) continue;
                        $res = $this->soutu->run(substr($data['file_name'], 1), substr($value['original_img'], 1));
                        if ($res < 5){
                            $arr['img'][] = $value['original_img'];
                        }
                    }
                    $arr['img_1'] = $data['file_name'];
                    echo json_encode($arr);
                }
            } else {
                $this->load->view('search_map');
            }
        }

        public function goods_e_sku()
        {
            $goods_id  = $this->input->post('goods_id');
            $goods_sku = $this->db->from('goods_sku')->where(['goods_id' => $goods_id, 'e_update' => 0, 'is_delete' => 0])->get()->result_array();
            echo json_encode($goods_sku);
        }

        public function goods_sku_examine()
        {

            $this->load->library('sys_message');
            if ( !$_SESSION['admin_id']){
                $this->sys_message->wrong('刷新页面');
            }
            // if ($_SESSION['admin_id'] != 2 && $_SESSION['admin_id'] != 79 && $_SESSION['admin_id'] != 29){
            //     $this->sys_message->wrong('负责人才能审核');
            // }

            $goods_id = $this->input->post('goods_id');
            if (empty($goods_id)){
                $this->sys_message->wrong('刷新页面');
            }
            $array = $this->db->from('goods_sku')->where(['goods_id' => $goods_id, 'e_update' => 0, 'is_delete' => 0])->get()->result_array();
            foreach ($array as $k => $v) {
                $goods          = $this->db->from('goods')
                                           ->where(['goods_id' => $v['goods_id']])
                                           ->select('cn_name,goods_name,type_id,in_price,goods_weight,suppliers_id,shop_price,supp_url,purchase_id,sale_status')
                                           ->get()->row_array();
                $type           = $this->db->from('goods_type')
                                           ->where(['cat_id' => $goods['type_id']])
                                           ->select('cat_name_zh,cat_name,cate_code')
                                           ->get()->row_array();
                $suppliers_name = $this->db->from('suppliers')
                                           ->where(['suppliers_id' => $goods['suppliers_id']])
                                           ->select('suppliers_name,suppliers_id')
                                           ->get()->row_array();
                // $goods_album = $this->db->from('goods_album')
                //         ->where(['goods_id'=>$v['goods_id'],'is_delete'=>0])
                //         ->select('original_img')
                //         ->get()->result_array();
                // $album = [];
                // foreach ($goods_album as $key => $val) {
                //     $album[] = 'http://sumerbikini.com'.$val['original_img'];
                // }
                $this->load->library('eccang');
                $info = $this->eccang->getSupplierInfo(['condition' => ['supplierName' => trim($suppliers_name['suppliers_name'])]]);
                if ( !empty($info['data'])){
                    $defaultSupplierCode = $info['data'][0]['supplierCode'];
                } else {
                    $defaultSupplierCode = 'G' . $suppliers_name['suppliers_id'];
                    $data                = [
                        'actionType' => 'ADD',
                        'supplier'   => [
                            'supplierCode'         => $defaultSupplierCode,
                            'supplierName'         => $suppliers_name['suppliers_name'],
                            'buyerId'              => $suppliers_name['suppliers_id'] % 2 == 1 ? 583 : 609,
                            'level'                => 'A',
                            'supplierTeamworkType' => 0,
                            'supplierType'         => 1,
                            'pcId'                 => 3,
                            'accountType'          => 2,
                            'payType'              => 1,
                            'supplierCarrier'      => 1,
                            'shippingMethodIdHead' => 2,
                            'supplierQcException'  => 2,
                            'accountProportion'    => 100,
                        ],
                    ];
                    $suppliers_e         = $this->eccang->syncSupplierInfo($data);
                    $this->db->where(['suppliers_id' => $suppliers_name['suppliers_id']]);
                    $this->db->update('suppliers', ['e_code' => $suppliers_e['data']['supplierCode']]);
                }

                $colors    = $this->db->from('colors')->where(['color_en' => $v['color']])->select('e_id')->get()->row_array();
                $size      = $this->db->from('size')->where(['size_value' => $v['size']])->select('e_id')->get()->row_array();
                $ali_color = !empty($v['ali_color']) ? $v['ali_color'] : $v['color'];
                $ali_size  = !empty($v['ali_size']) ? $v['ali_size'] : $v['size'];
                $res       = [];

                $res['actionType']                 = 'ADD';
                $res['productSku']                 = $v['sku_sn'];
                $res['productTitle']               = $goods['cn_name'] . '---' . $ali_color . '/' . $ali_size;
                $res['productTitleEn']             = $goods['goods_name'];
                $res['pdOverseaTypeCn']            = $type['cat_name_zh'];
                $res['pdOverseaTypeEn']            = $type['cat_name'];
                $res['productDeclaredValue']       = 1.5;
                $res['pdDeclareCurrencyCode']      = 'USD';
                $res['productPurchaseValue']       = (Float)$goods['in_price'];
                $res['productPurchaseValueNotTax'] = (Float)$goods['in_price'];
                $res['currencyCode']               = 'RMB';
                $res['productWeight']              = $goods['goods_weight'] < 50 ? 0.05 : $goods['goods_weight'] / 1000;
                $res['defaultSupplierCode']        = $defaultSupplierCode;
                $res['productPrice']               = $goods['shop_price'];
                $res['oprationType']               = 2;
                $res['productStatus']              = 1;
                $res['saleStatus']                 = $goods['sale_status'] ?: 2;
                $res['hsCode']                     = $type['cate_code'];
                $res['productLength']              = 1;
                $res['productWidth']               = 1;
                $res['productHeight']              = 1;
                $res['personOpraterId']            = $goods['purchase_id'];
                $res['productColorId']             = $colors['e_id'];
                $res['productSizeId']              = $size['e_id'];
                $res['spMinQty']                   = 1;
                $res['spProductAddress']           = $goods['supp_url'];
                $res['productImgUrlList']          = [config_item('base_url') . $v['album_url']];
                $info                              = $this->eccang->add_syncProduct($res);
                if ($info['code'] == 200 || ($info['code'] == 500 && $info['error'][0]['errorMsg'] == '产品' . $v['sku_sn'] . '已经存在')){//处理e仓接口易仓导致商品已经创建成功
                    //            if($info['code'] == 200){
                    $this->db->where(['sku_id' => $v['sku_id']]);
                    $this->db->update('goods_sku', ['e_update' => 1]);
                }
            }
            $this->sys_message->success('成功');
        }

        public function syncProduct_edit_img()
        {
            $this->load->library('sys_message');
            $this->load->library('eccang');
            $goods_id  = $this->input->post('goods_id');
            $goods_sku = $this->db->from('goods_sku')->where(['goods_id' => $goods_id, 'e_update' => 2, 'is_delete' => 0])->select('album_url,sku_num_sn')->get()->result_array();

            $goods = $this->db->from('goods')->where(['goods_id' => $goods_id])->select('type_id')->get()->row_array();
            $type  = $this->db->from('goods_type')
                              ->where(['cat_id' => $goods['type_id']])
                              ->select('cat_name_zh,cat_name,cate_code')
                              ->get()->row_array();
            foreach ($goods_sku as $key => $value) {
                $productImgUrlList   = array();
                $productSku          = $value['sku_num_sn'];
                $productImgUrlList[] = config_item('base_url') . $value['album_url'];
                $pdOverseaTypeCn     = $type['cat_name_zh'];
                $pdOverseaTypeEn     = $type['cat_name'];
                $this->eccang->syncProduct_edit_img($productSku, $productImgUrlList, $pdOverseaTypeCn, $pdOverseaTypeEn);
            }
            $this->db->where(['goods_id' => $goods_id, 'e_update' => 2, 'is_delete' => 0]);
            $this->db->update('goods_sku', ['e_update' => 1]);
            $this->sys_message->success('成功');
        }


        /**
         * e仓规格图片更新
         */
        public function syncProduct_attr_img()
        {
            $this->load->library('sys_message');
            $this->load->library('eccang');
            $goods_id = $this->input->post('goods_id');
            //        $goods_sku = $this->db->from('goods_sku')->where(['goods_id'=>$goods_id,'e_update'=>1,'is_delete'=>0])->select('album_url,sku_num_sn')->get()->result_array();
            $goods_sku = $this->db->from('goods_sku')->where(['goods_id' => $goods_id])->select('sku_sn,album_url,sku_num_sn,ali_color,ali_size')->get()->result_array();

            $goods = $this->db->from('goods')->where(['goods_id' => $goods_id])->select('in_price,supp_url,suppliers_id,type_id,sale_status,cn_name,purchase_id')->get()->row_array();
            $saleStatus = $goods['sale_status'];
            $type       = $this->db->from('goods_type')
                                   ->where(['cat_id' => $goods['type_id']])
                                   ->select('cat_name_zh,cat_name,cate_code')
                                   ->get()->row_array();
            //查询供应商e_code不存在就添加供应商到e仓否则就修改表
            $e_code = $this->db->from('suppliers')->where(['suppliers_id' => $goods['suppliers_id']])->select('suppliers_id,suppliers_name,e_code,suppliers_name')->get()->row_array();
            if(empty($e_code['e_code'])){
                //code不存在查询E仓信息
                $supplierName = $this->eccang->getSupplierInfo(['condition'=>['supplierName'=>$e_code['suppliers_name']]]);
                //如果supplierName不存在添加
                if(empty($supplierName['data'])){
                    $data = ['actionType'=>'ADD','supplier'=>[
                        'supplierCode'=>'G'.$e_code['suppliers_id'],
                        'supplierName'=>$e_code['suppliers_name'],
                        'buyerId'=>$goods['purchase_id'],
                        'level'=>'A',
                        'supplierTeamworkType'=>0,
                        'supplierType'=>1,
                        'pcId'=>3,
                        'accountType'=>2,
                        'payType'=>1,
                        'supplierCarrier'=>1,
                        'shippingMethodIdHead'=>2,
                        'supplierQcException'=>2,
                        'accountProportion'=>100
                    ]];
                    $re = $this->eccang->syncSupplierInfo($data);
                    $e_code['e_code'] = $re['data']['supplierCode'];

                }else{
                    $e_code['e_code'] = $supplierName['data'][0]['supplierCode'];
                }
                $this->db->where(['suppliers_name'=>$e_code['suppliers_name']]);
                $this->db->update('suppliers',['e_code'=>$e_code['e_code']]);
            }
            //获取货品的规格图片
            //$this->load->library('good');
            /** @var good $good_lib */
            //$good_lib = $this->good;
            //$img_url  = $good_lib->get_sku_attr_img($goods_sku[0]['sku_num_sn']);

            foreach ($goods_sku as $key => $value) {
                $productImgUrlList   = array();
                // $productImgUrlList[] = $img_url;
                $productImgUrlList[] = config_item('base_url') . $value['album_url'];


                $productSku      = $value['sku_sn'];
                $productTitle = $goods['cn_name'].'---'.$value['ali_color'].'/'.$value['ali_size'];
                $pdOverseaTypeCn = $type['cat_name_zh'];
                $pdOverseaTypeEn = $type['cat_name'];
                $spProductAddress = $goods['supp_url'];
                $personOpraterId = $goods['purchase_id'];
                $this->eccang->syncProduct_attr_img($productSku, $productImgUrlList, $pdOverseaTypeCn, $pdOverseaTypeEn,$productTitle,$personOpraterId);
                $this->eccang->syncEditSaleStatus($productSku, $saleStatus, $pdOverseaTypeCn, $pdOverseaTypeEn,$spProductAddress,$e_code['e_code'],$goods['in_price']);
            }
            $this->db->where(['goods_id' => $goods_id, 'e_update' => 2, 'is_delete' => 0]);
            $this->db->update('goods_sku', ['e_update' => 1]);
            $this->sys_message->success('成功');
        }

        public function img_list(){
            $goods_id = $this->input->post('goods_id');
            $album = $this->db->from('goods_album')->where(['goods_id'=>$goods_id])->select('original_img')->get()->result_array();
            echo json_encode($album);
        }

        public function goods_sku_list(){
            $_param_option = array(
                'sku' => array(
                    'col'         => 'col-lg-3',
                    'type'        => 'text',
                    'placeholder' => 'sku搜索',
                ),
            );
            $sku = $this->input->get('sku');
            if($sku){
                $goods_sku = $this->db->from('goods_sku')->where(['sku_sn'=>$sku])->get()->result_array();
            }
            
            $data = array(
                'sku_list'           => $goods_sku,
                'param_option'         => $_param_option,
            );

            $this->load->view('goods_sku_list', $data);
        }

        public function baby_goods(){
            $this->config->load('website_common');
            $this->load->library('session');
            $this->load->model('goods_model');
            $this->load->model('admin_model');
            $this->load->model('suppliers_model');
            $this->load->model('size_model');
            $this->load->model('color_model');
            $this->load->library('sys_message');
            $config = $this->config->item('upload');
            $this->load->library('upload', $config);
            $this->load->library('image_lib');
            if ($_POST){
                $data = array(
                    'baby_goods_name'       => trim($this->input->post('cn_name')), //商品名称
                    'baby_channel'          => trim($this->input->post('channel_id')),  //渠道
                    'baby_gooda_supplier'   => trim($this->input->post('suppliers_id')), //供应商ID
                    'baby_admin_id'          => trim($this->input->post('admin_id')), //添加人ID
                    'baby_goods_sn'      => $this->input->post('goods_sn'),//货号
                    'baby_goods_link'     => $this->input->post('supp_url'),//商品链接
                    'baby_goods_weight'       => $this->input->post('goods_weight'),//商品重量
                    'baby_goods_enter_price'         => $this->input->post('in_price'),//进价
                    'baby_goods_original_price'     => $this->input->post('market_price'),//原价
                    'baby_goods_price'     => $this->input->post('shop_price'),//售价
                    'baby_goods_describe'         => $this->input->post('summernote'),//描述
                    'baby_add_time'          => time(),//添加时间
                );
                $this->db->insert('baby_goods',$data);
                $id = $this->db->insert_id();



                $files_sort = $this->input->post('files_sort');
                !$files_sort && $this->sys_message->wrong('请上传图片!');
                foreach ($files_sort as $k => $val) {
                    if ($this->upload->do_upload('files' . $k)){
                        $data_images            = $this->upload->data();
                        $img['baby_goods_img'] = $data_images['file_name'];
                        $img['baby_add_time'] = time();
                        $img['baby_goods_id'] = $id;
                        $this->db->insert('baby_goods_img',$img);
                    }
                }

                $sku = $this->input->post('sku');
                foreach ($sku['size'] as $key => $val) {
                    if($val){
                        foreach ($sku['color'] as $k => $v){
                            if($v){
                                $baby_sku = ['baby_sku_head'=>$val,'baby_sku_size'=>$v,'baby_goods_id'=>$id];
                                $this->db->insert('baby_goods_sku',$baby_sku);
                            }
                        }
                    }
                }
                $this->sys_message->success('成功!');
                



            }else{
                $size   = $this->size_model->size_option();
                $colors = $this->color_model->color_option();
                $size_option      = $size['option'];
                $color_option     = $colors['option'];
                $suppliers_option = $this->suppliers_model->suppliers_option();
                $admin_id         = $this->session->userdata('admin_id');
                $goods_sn         = $this->goods_model->goods_sn_max($admin_id);
                $admin_name       = $this->admin_model->admin_option();
                $data = array(
                    'suppliers_option' => $suppliers_option,
                    'size_option'      => $size_option,
                    'goods_sn'         => $goods_sn,
                    'color_option'     => $color_option,
                    'admin_name'       => $admin_name,
                    'admin_id'         => $admin_id,
                );

                $this->load->view('baby_goods', $data);
            }            
        }

        public function goods_web_volume_count(){
            $siteweb_arr = $this->db->from('siteweb')->where(['is_delete'=>0,'type'=>1])->select('web_id,web_name')->get()->result_array();
            $siteweb = array();
            foreach ($siteweb_arr as $key => $val) {
                $siteweb[$val['web_id']] = $val['web_name'];
            }
            $_param_option = array(
                'siteweb'     => array(
                    'type'        => 'option',
                    'option'      => $siteweb,
                ),
            );

            if($this->input->get('siteweb') > 0){
                $assoc = $this->uri->uri_to_assoc();
                $_param = array(
                    'siteweb'        => intval($this->input->get('siteweb')),
                    'page' => $assoc['page'] > 0 ? intval($assoc['page']) - 1 : 0,
                    'add_time_start'        => $this->input->get('add_time_start'),
                    'add_time_end'        => $this->input->get('add_time_end'),
                );
                $count_sql = "SELECT og.goods_id,count(*) FROM pcs_order_info as oi LEFT JOIN pcs_order_goods as og ON oi.order_id = og.order_id WHERE oi.web_id = 1 GROUP BY(og.goods_id)";
                $count = $this->db->query($count_sql)->result_array();
                $page_count = ceil(count($count) / 15);

                if($_param['page'] >= $page_count){

                    $_param['page'] = $page_count;
                    $_param['page'] = $_param['page'] -1;
                }

                $sql = "SELECT og.goods_id,count(*) as count,sum(og.goods_number) as sum FROM pcs_order_info as oi LEFT JOIN pcs_order_goods as og ON oi.order_id = og.order_id";

                if($_param['siteweb'] > 0){
                    $sql .= ' WHERE oi.web_id ='.$_param['siteweb'];
                }

                if ($_param['add_time_start'] && $_param['add_time_end']) {
                    $_param['add_time_start'] = strtotime($_param['add_time_start']);
                    $_param['add_time_end'] = strtotime($_param['add_time_end']);

                    $sql .= ' AND oi.add_time >= '.$_param['add_time_start'].' and oi.add_time <= '.$_param['add_time_end'];
                }

                $sql .= ' GROUP BY(og.goods_id) ORDER BY count desc LIMIT '. $_param['page'] * 15 .',15';
                // echo $sql;die;
                $res = $this->db->query($sql)->result_array();
                foreach ($res as $k => $v) {
                    $goods_info = $this->db->from('goods')->where(['goods_id'=>$v['goods_id']])->select('goods_sn,original_img')->get()->row_array();
                    $res[$k]['goods_sn'] = $goods_info['goods_sn'];
                    $res[$k]['original_img'] = $goods_info['original_img'];
                }
                

                $data = array(
                    'param_option' => $_param_option,
                    'goods_count'  =>$res,
                    'page'  =>$_param['page'],
                    'siteweb'=>$_param['siteweb'],
                    'param'=>$_param,
                );
            }else{
                $data = array(
                    'param_option' => $_param_option,
                );
            }
            $this->load->view('goods_web_volume_count',$data);
        }
    }
